package com.hvisions.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hvisions.entity.Role;
import com.hvisions.entity.User;
import com.hvisions.service.IRoleService;
import com.hvisions.service.IUserService;
import com.hvisions.shiro.MyShiroRealm;
import com.hvisions.util.*;
import com.hvisions.vo.base.PageResultVo;
import com.hvisions.vo.base.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Author: Lau
 * @Description: 用户管理
 * @Date: Created in 15:54 2019/10/25
 * @Modified By:
 */
@Controller()
@RequestMapping("/user")
public class UserController {


    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @Autowired
    private MyShiroRealm shiroRealm;

    /**
     * 获取用户列表
     * @param offset 偏移量
     * @param size  每页显示的条数
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public PageResultVo getUserList(User user, Integer offset, Integer size){
        PageHelper.startPage(PageUtil.getpageNum(size,offset),size);
        List<User> userList = userService.selectUsers(user);
        PageInfo<User> pages = new PageInfo<>(userList);
        return ResultUtil.table(userList,pages.getTotal());
    }

    @ResponseBody
    @PostMapping("/add")
    public ResponseVo addUser(User userform,String confirmPassword){
        String username = userform.getUsername();
        User user = userService.selectByUsername(username);
        if(user!=null){
            return ResultUtil.error("用户名已存在");
        }
        String password = userform.getPassword();
        if(confirmPassword != null && password != null && !password.equals(confirmPassword)){
            return ResultUtil.error("两次密码不一致");
        }
        userform.setUserId(UUIDUtil.getUniqueIdByUUId());
        userform.setStatus(CoreConst.STATUS_VALID);
        Date date = new Date();
        userform.setCreateTime(date);
        userform.setUpdateTime(date);
        userform.setLastLoginTime(date);
        PasswordHelper.encryptPassword(userform);
        int num = userService.register(userform);
        if(num>0){
            return ResultUtil.success("添加用户成功");
        }else{
            return ResultUtil.error("添加用户失败");
        }
    }

    /**删除用户*/
    @GetMapping("/delete")
    @ResponseBody
    public ResponseVo deleteUser(String userId) {
        List<String> userIdsList = Arrays.asList(userId);
        int a = userService.updateStatusBatch(userIdsList,CoreConst.STATUS_INVALID);
        if (a > 0) {
            return ResultUtil.success("删除用户成功");
        } else {
            return ResultUtil.error("删除用户失败");
        }
    }

    /**批量删除用户*/
    @GetMapping("/batch/delete")
    @ResponseBody
    public ResponseVo batchDeleteUser(String userIdStr) {
        String[] userIds = userIdStr.split(",");
        List<String> userIdsList = Arrays.asList(userIds);
        int a = userService.updateStatusBatch(userIdsList,CoreConst.STATUS_INVALID);
        if (a > 0) {
            return ResultUtil.success("删除用户成功");
        } else {
            return ResultUtil.error("删除用户失败");
        }
    }


    /**编辑用户页面跳转*/
    @GetMapping("/edit")
    public String userDetail(Model model, String userId){
        User user = userService.selectByUserId(userId);
        model.addAttribute("user", user);
        return "user/userDetail";
    }


    /**编辑用户*/
    @PostMapping("/edit")
    @ResponseBody
    public ResponseVo editUser(User userForm){
        int a = userService.updateByUserId(userForm);
        if (a > 0) {
            return ResultUtil.success("编辑用户成功！");
        } else {
            return ResultUtil.error("编辑用户失败");
        }
    }


    /**分配角色列表查询*/
    @PostMapping("/assign/role/list")
    @ResponseBody
    public Map<String,Object> assignRoleList(String userId){
        List<Role> roleList = roleService.selectRoles(new Role());
        Set<String> hasRoles = roleService.findRoleByUserId(userId);
        Map<String, Object> jsonMap = new HashMap<>(2);
        jsonMap.put("rows", roleList);
        jsonMap.put("hasRoles",hasRoles);
        return jsonMap;
    }

    /**
     * 保存重新分配的角色
     * @param userId  用户id
     * @param roleIdStr 角色id
     * @return
     */
    @PostMapping("/assign/role")
    @ResponseBody
    public ResponseVo assignRole(String userId, String roleIdStr){
        String[] roleIds = roleIdStr.split(",");
        List<String> roleIdsList = Arrays.asList(roleIds);
        ResponseVo responseVo = userService.addAssignRole(userId,roleIdsList);
        List<String> userIds = new ArrayList<>();
        userIds.add(userId);
        shiroRealm.clearAuthorizationByUserId(userIds);
        return responseVo;
    }
}
